import { Injectable } from "@angular/core";
import { BaseHttpService } from "../../../shared/services/baseHttp.service";
import { Observable } from "rxjs";
import { EventType, EventResponseModel, EventModel } from "./models/events.model";
import { HttpParams, HttpClient } from "@angular/common/http";

@Injectable()
export class EventsService extends BaseHttpService {
    constructor(private http: HttpClient) {
        super()
    }

    public getEventsList(term: string, eventType: EventType, skip: number, take: number): Observable<EventResponseModel> {
        let params = new HttpParams();
        params = params.set('term', term)
            .set('eventType', eventType ? EventType[eventType].toString() : '')
            .set('skip', skip.toString())
            .set('take', take.toString())
            .set('includeAllFields', false.toString())
            .set('getCount', '')
            .set('orderBy', 'StartDate')
            .set('orderAscending', false.toString());

        return this.http.get<EventResponseModel>(this.serverUrl + '/eventsserv/api/v1/events', { params: params });
    }

    public getEventsCount(term: string, eventType: EventType): Observable<number> {
        let params = new HttpParams();
        params = params.set('term', term)
            .set('eventType', eventType ? EventType[eventType].toString() : '')
            .set('skip', '')
            .set('take', '')
            .set('includeAllFields', false.toString())
            .set('getCount', true.toString())
            .set('orderBy', '')
            .set('orderAscending', false.toString());

        return this.http.get<any>(this.serverUrl + '/eventsserv/api/v1/events', { params: params }).map(x => x.count);
    }

    public publishEvents(ids: string[]): Observable<void> {
        return this.http.patch<void>(this.serverUrl + '/eventsserv/api/v1/events', { publishItems: ids });
    }

    public deleteEvents(ids: string[]): Observable<void> {
        return this.http.patch<void>(this.serverUrl + '/eventsserv/api/v1/events', { deleteItems: ids });
    }

    public getEvent(id: string): Observable<EventModel> {        
        return this.http.get<EventModel>(this.serverUrl + '/eventsserv/api/v1/events/' + id);
    }

    public publishEvent(event: EventModel): Observable<EventModel>{
        return this.http.post<EventModel>(this.serverUrl + '/eventsserv/api/v1/events', event);
    }
    
    public saveEvent(event: EventModel): Observable<EventModel>{
        return this.http.put<EventModel>(this.serverUrl + '/eventsserv/api/v1/events', event);
    }
}